import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vdrag_saas/Utils.dart';
import 'package:vdrag_saas/detail/device_util.dart';
import 'package:vdrag_saas/detail/share_util.dart';
import 'package:vdrag_saas/model/product.dart';

class UseProduct extends StatefulWidget {
  Product product;
  bool showQR = false;
  String label = '立即体验';
  UseProduct(this.product,
      {super.key, this.showQR = false, this.label = "立即体验"});

  @override
  State<StatefulWidget> createState() => _UseProduct();
}

class _UseProduct extends State<UseProduct> {
  Offset? menuPosition;

  // 请求权限
  Future<bool> requestPermissions() async {
    // 请求存储权限
    PermissionStatus status = await Permission.storage.request();

    if (status.isGranted) {
      return true;
    } else if (status.isPermanentlyDenied) {
      return false;
    } else if (status.isDenied) {
      return false;
    }
    return false;

    // 同理，你可以请求其他权限，例如相机权限
    // PermissionStatus cameraStatus = await Permission.camera.request();
  }

  void showPopupMenu(BuildContext context, LongPressStartDetails details) {
    bool isMobile = DeviceUtil.isMobile;
    if (!isMobile) {
      return;
    }
    RenderBox box = context.findRenderObject() as RenderBox;
    setState(() {
      menuPosition = details.globalPosition;
    });
    if (menuPosition == null) {
      return;
    }
    final targetGlobalPosition = box.localToGlobal(Offset.zero);
    final relativeOffset = menuPosition! - targetGlobalPosition;
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(relativeOffset.dx, relativeOffset.dy,
          relativeOffset.dx + 100, relativeOffset.dx + 100),
      items: [
        PopupMenuItem(
            onTap: () async {
              bool needSave = await requestPermissions();
              if (!needSave) {
                return;
              }
              try {
                final byteData = await rootBundle.load('assets/images/qr.png');
                // Directory directory = '';
                String downloadDir = '/storage/emulated/0/Pictures/GEOVIS';
                Directory dir = Directory(downloadDir);
                if (!await dir.exists()) {
                  await dir.create();
                }
                final file = File('$downloadDir/geovis.jpg');
                await file.writeAsBytes(byteData.buffer.asUint8List(
                    byteData.offsetInBytes, byteData.lengthInBytes));
                MethodChannel channel = const MethodChannel('com.example.refresh_media_store');
                channel.invokeMethod('refresh', {'path': '$downloadDir/geovis.jpg'});
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('图片已经保存到Pictures/GEOVIS路径下'),
                  ),
                );
              } catch (e) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('图片保存失败'),
                  ),
                );
              }
            },
            child: const Text("保存图片")),
        PopupMenuItem(
            onTap: () async {
              final byteData = await rootBundle.load('assets/images/qr.png');
              final tempDir = await getTemporaryDirectory();
              final tempFile = File('${tempDir.path}/temp_image.png');
              await tempFile.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
              await Share.shareFiles(['${tempDir.path}/temp_image.png']);
            },
            child: const Text("分享图片"))
      ],
    );
  }

  openDialog(bool isMobile, BuildContext context) async {
    showDialog<bool?>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            surfaceTintColor: Colors.transparent,
            backgroundColor: Colors.white,
            contentPadding: const EdgeInsets.only(top: 10, bottom: 44),
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadiusDirectional.all(Radius.circular(4))),
            title: const Column(children: [
              Text('温馨提示',
                  style: TextStyle(
                      fontFamily: '思源黑体',
                      fontSize: 17,
                      fontWeight: FontWeight.w500)),
              Padding(padding: EdgeInsets.symmetric(vertical: 8)),
              Text('您可添加下方微信进行详细咨询',
                  style: TextStyle(
                      fontFamily: '思源黑体',
                      fontSize: 12,
                      fontWeight: FontWeight.w400))
            ]),
            content: Column(mainAxisSize: MainAxisSize.min, children: [
              GestureDetector(
                onLongPressStart: (LongPressStartDetails details) {
                  showPopupMenu(context, details);
                },
                child: Image.asset('assets/images/qr.png'),
              ),
              Visibility(visible: isMobile, child: const Text('长按保存二维码'))
            ]),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    bool isMobile = Utils.isMobile(context);
    EdgeInsets padding =
        const EdgeInsets.symmetric(vertical: 6, horizontal: 12);
    if (!isMobile) {
      padding = const EdgeInsets.symmetric(vertical: 16, horizontal: 45);
    }
    return FilledButton(
        style: ButtonStyle(
            // fixedSize: const MaterialStatePropertyAll(Size(200, 40)),
            minimumSize: const MaterialStatePropertyAll(Size.zero),
            padding: MaterialStateProperty.all(padding),
            backgroundColor:
                MaterialStateProperty.all(const Color(0xff216EFF))),
        onPressed: () async {
          if (widget.showQR) {
            return await openDialog(isMobile, context);
          }
          String homeLink = widget.product.homeLink;
          Uri url = Uri.parse(homeLink);
          if (homeLink.isNotEmpty) {
            if (isMobile) {
              // ShareUnti.share(homeLink, context);
              Share.share(homeLink);
            } else {
              launchUrl(url);
            }
            return;
          }
          await openDialog(isMobile, context);
          // print('我想体验$homeLink');
        },
        child: Text(widget.label,
            style: const TextStyle(color: Color(0xffffffff))));
  }
}
